# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-04 23:40
# File     : project.py
# Project  : codebuddy_craft
# Desc     : 项目模型

# backend/models/project.py
from sqlalchemy import Column, String, Text, Boolean, JSON, ForeignKey, DateTime, Enum, Integer
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from datetime import datetime
import uuid
import enum

from backend.database.connection import Base


class ProjectStatus(enum.Enum):
    """项目状态枚举"""
    ACTIVE = "active"
    ARCHIVED = "archived"
    DELETED = "deleted"


class ProjectVisibility(enum.Enum):
    """项目可见性枚举"""
    PRIVATE = "private"
    PUBLIC = "public"
    TEAM = "team"


class CollaboratorRole(enum.Enum):
    """协作者角色枚举"""
    OWNER = "owner"
    ADMIN = "admin"
    DEVELOPER = "developer"
    VIEWER = "viewer"


class Project(Base):
    """项目模型 📁"""
    __tablename__ = "projects"

    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    name = Column(String(100), nullable=False)
    description = Column(Text)

    # 项目配置
    tech_stack = Column(JSON, default=[])  # 技术栈
    status = Column(Enum(ProjectStatus), default=ProjectStatus.ACTIVE)
    visibility = Column(Enum(ProjectVisibility), default=ProjectVisibility.PRIVATE)

    # 项目设置
    settings = Column(JSON, default={})
    tags = Column(JSON, default=[])

    # 统计信息
    file_count = Column(Integer, default=0)
    total_lines = Column(Integer, default=0)

    # 关联用户
    owner_id = Column(String(36), ForeignKey("users.id"), nullable=False)

    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    last_accessed_at = Column(DateTime(timezone=True))

    # 关系
    owner = relationship("User", back_populates="projects")
    files = relationship("File", back_populates="project", cascade="all, delete-orphan")
    collaborators = relationship("ProjectCollaborator", back_populates="project", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<Project(id={self.id}, name={self.name})>"

    def to_dict(self, include_files=False):
        """转换为字典"""
        result = {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'tech_stack': self.tech_stack,
            'status': self.status.value,
            'visibility': self.visibility.value,
            'settings': self.settings,
            'tags': self.tags,
            'file_count': self.file_count,
            'total_lines': self.total_lines,
            'owner_id': self.owner_id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'last_accessed_at': self.last_accessed_at.isoformat() if self.last_accessed_at else None
        }

        if include_files:
            result['files'] = [file.to_dict() for file in self.files]

        return result


class ProjectCollaborator(Base):
    """项目协作者模型 🤝"""
    __tablename__ = "project_collaborators"

    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    project_id = Column(String(36), ForeignKey("projects.id"), nullable=False)
    user_id = Column(String(36), ForeignKey("users.id"), nullable=False)
    role = Column(Enum(CollaboratorRole), nullable=False)

    # 权限设置
    permissions = Column(JSON, default={})

    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # 关系
    project = relationship("Project", back_populates="collaborators")
    user = relationship("User", back_populates="project_collaborations")

    def __repr__(self):
        return f"<ProjectCollaborator(project_id={self.project_id}, user_id={self.user_id}, role={self.role})>"


class ProjectTemplate(Base):
    """项目模板模型 📋"""
    __tablename__ = "project_templates"

    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    name = Column(String(100), nullable=False)
    description = Column(Text)

    # 模板配置
    tech_stack = Column(JSON, default=[])
    template_files = Column(JSON, default={})  # 文件名 -> 文件内容

    # 模板设置
    is_public = Column(Boolean, default=True)
    category = Column(String(50))
    tags = Column(JSON, default=[])

    # 统计
    usage_count = Column(Integer, default=0)

    # 创建者
    created_by = Column(String(36), ForeignKey("users.id"))

    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    def __repr__(self):
        return f"<ProjectTemplate(id={self.id}, name={self.name})>"

